package com.platform.api;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.jfinal.aop.Duang;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.Prop;
import com.jfinal.kit.StrKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.PaymentApi;
import com.jfinal.weixin.sdk.kit.IpKit;
import com.jfinal.weixin.sdk.kit.PaymentKit;
import com.jfinal.wxaapp.api.WxaTemplate;
import com.jfinal.wxaapp.api.WxaTemplateApi;
import com.platform.annotation.IgnoreAuth;
import com.platform.annotation.LoginUser;
import com.platform.entity.*;
import com.platform.service.ApiCommonwealService;
import com.platform.service.ApiDonationRecordService;
import com.platform.service.ApiUserService;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiPageUtils;
import com.platform.utils.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.platform.config.Constants.SuccessfulDonation;
import static com.platform.util.CommonUtil.getProp;
import static com.platform.util.wechat.WechatUtil.setWxaConfig;

/**
 * 作者: @author czj <br>
 * 时间: 2018-11-01 08:32<br>
 * 描述: 公益活动 <br>
 */
@RestController
@RequestMapping("/api/commonweal")
public class ApiCommonwealController extends ApiBaseAction {
    @Autowired
    private ApiCommonwealService commonwealService;

    @Autowired
    private ApiUserService userService;

    @Autowired
    private ApiDonationRecordService donationRecordService;

    static Prop prop = getProp();
    String appid = prop.get("payAppId");
    String partner = prop.get("payMchId");
    String paternerKey = prop.get("payPaternerKey");
    String notify_url = prop.get("payCallBackDomain") + "/api/commonweal/pay_notify";

    @IgnoreAuth
    @RequestMapping(value = "list", method = {RequestMethod.GET, RequestMethod.POST})
    public Object list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "size", defaultValue = "10") Integer size, Integer isHot) {
        Map<String, Object> param = new HashMap<>();
        param.put("page", page);
        param.put("limit", size);
        param.put("is_delete", 0);//是否已删除：1-是；0-否
        if (isHot != null) {
            param.put("is_hot", 0);//是否热门：1-是；0-否
        }
        param.put("sidx", "id");
        param.put("order", "desc");

        Query query = new Query(param);
        List<CommonwealVo> topicEntities = commonwealService.queryList(query);
        int total = commonwealService.queryTotal(query);
        ApiPageUtils pageUtil = new ApiPageUtils(topicEntities, total, query.getLimit(), query.getPage());

        return toResponsSuccess(pageUtil);
    }

    @IgnoreAuth
    @RequestMapping(value = "detail", method = {RequestMethod.GET, RequestMethod.POST})
    public Object detail(@RequestParam(value = "id") Integer id) {
        CommonwealVo commonwealVo = commonwealService.queryObject(id);
        if (commonwealVo == null) {
            return toResponsFail("不存在该公益活动");
        }
        //
        if (commonwealVo.getIsDelete() == 1) {
            return toResponsFail("活动已删除");
        }

        return toResponsSuccess(commonwealVo);
    }


    //温暖捐款
    @RequestMapping(value = "warmDonation", method = {RequestMethod.POST})
    public Object warmDonation(@LoginUser UserVo loginUser,
                               @RequestParam("donorAmount") String donorAmount,
                               @RequestParam("isAnonymous") Integer isAnonymous,
                               @RequestParam("commonwealId") Integer commonwealId,
                               String donorName) {
        //验证传递进来的金额是否数字
        if (!Validator.isNumber(donorAmount)) {
            return toResponsFail("请填写正确的金额");
        }

        if (isAnonymous == 0) {//是否匿名：1-是；0-否
            if (Validator.isEmpty(donorName)) {
                return toResponsFail("请填写您的姓名");
            }

            if (donorName.length() > 20) {
                return toResponsFail("姓名最长20字符");
            }
        }

        CommonwealVo commonwealVo = commonwealService.queryObject(commonwealId);
        if (commonwealVo == null) {
            return toResponsFail("不存在该活动");
        }
        if (commonwealVo.getIsExpired() == 1) {
            return toResponsFail("活动已过期");
        }
        if (commonwealVo.getIsDelete() == 1) {
            return toResponsFail("活动已删除");
        }

        //保存捐款记录
        DonationRecordVo donationRecordVo = new DonationRecordVo();
        donationRecordVo.setUserId(loginUser.getUserId().intValue());
        donationRecordVo.setUserNickname(loginUser.getNickname());
        donationRecordVo.setCommonwealId(commonwealId);
        donationRecordVo.setCommonwealName(commonwealVo.getTitle());
        donationRecordVo.setDonorName(donorName);
        donationRecordVo.setDonorAmount(new BigDecimal(donorAmount));
        donationRecordVo.setIsAnonymous(isAnonymous);
        donationRecordVo.setIsPay(0);//是否已支付：1-是；0-否
        donationRecordVo.setAddTime(new Date());
        donationRecordService.save(donationRecordVo);

        //发起支付
        String openId = loginUser.getWeixin_openid();

        if (Validator.isEmpty(openId)) {
            return toResponsFail("请先授权登录");
        }

        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", appid);
        params.put("mch_id", partner);
        params.put("body", "温暖捐款");
        String out_trade_no = System.currentTimeMillis() + "";
        params.put("out_trade_no", out_trade_no);
        int price = ((int) (Float.valueOf(donorAmount) * 100));
        params.put("total_fee", price + "");
        params.put("attach", donationRecordVo.getId().toString());
        String ip = IpKit.getRealIp(request);
        if (StrKit.isBlank(ip)) {
            ip = "127.0.0.1";
        } else {
            String[] split = ip.split(",");
            ip = split[0];
        }
        params.put("spbill_create_ip", ip);
        params.put("trade_type", PaymentApi.TradeType.JSAPI.name());
        params.put("nonce_str", System.currentTimeMillis() / 1000 + "");
        params.put("notify_url", notify_url);
        params.put("openid", openId);
        String sign = PaymentKit.createSign(params, paternerKey);

        params.put("sign", sign);

        String xmlResult = PaymentApi.pushOrder(params);

        System.out.println(xmlResult);

        Map<String, String> result = PaymentKit.xmlToMap(xmlResult);

        String return_code = result.get("return_code");
        String return_msg = result.get("return_msg");
        if (StrKit.isBlank(return_code) || !"SUCCESS".equals(return_code)) {
            return toResponsFail("支付失败," + "return_code:" + return_msg);
        }
        String result_code = result.get("result_code");
        if (StrKit.isBlank(result_code) || !"SUCCESS".equals(result_code)) {
            return toResponsFail("支付失败," + "result_code:" + return_msg);

        }
        // 以下字段在return_code 和result_code都为SUCCESS的时候有返回
        String prepay_id = result.get("prepay_id");

        logger.info("prepay_id:" + prepay_id);

        //处理业务
        donationRecordVo.setOutTradeNo(out_trade_no);
        donationRecordVo.setPrepayId(prepay_id);
        donationRecordService.update(donationRecordVo);


        Map<String, String> packageParams = new HashMap<>();
        packageParams.put("appId", appid);
        packageParams.put("timeStamp", System.currentTimeMillis() / 1000 + "");
        packageParams.put("nonceStr", System.currentTimeMillis() + "");
        packageParams.put("package", "prepay_id=" + prepay_id);
        packageParams.put("signType", "MD5");

        String packageSign = PaymentKit.createSign(packageParams, paternerKey);
        packageParams.put("paySign", packageSign);

        return toResponsSuccess(packageParams);
    }

    @IgnoreAuth
    @RequestMapping(value = "pay_notify", method = {RequestMethod.GET, RequestMethod.POST})
    public Object pay_notify(HttpServletRequest request, HttpServletResponse response) {

        // 支付结果通用通知文档: https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_7
        String xmlMsg = HttpKit.readData(request);

        System.out.println("支付通知=" + xmlMsg);

        Map<String, String> params = PaymentKit.xmlToMap(xmlMsg);

        // 微信支付订单号
        String transaction_id = params.get("transaction_id");
        String result_code = params.get("result_code");
        String openId = params.get("openid");
        // 商户订单号
        String out_trade_no = params.get("out_trade_no");
        ///////////////////////////// 以下是附加参数///////////////////////////////////

        String recordId = params.get("attach");
        String fee_type = params.get("fee_type");
        String is_subscribe = params.get("is_subscribe");
        String err_code = params.get("err_code");
        String err_code_des = params.get("err_code_des");

        // 注意重复通知的情况，同一订单号可能收到多次通知，请注意一定先判断订单状态
        // 避免已经成功、关闭、退款的订单被再次更新
        try {
            if (result_code.equalsIgnoreCase("FAIL")) {
                //订单编号
                logger.error("订单" + out_trade_no + "支付失败");
            } else if (result_code.equalsIgnoreCase("SUCCESS")) {
                //订单编号
                logger.info("订单:" + out_trade_no + "支付成功");
                // 业务处理
                DonationRecordVo donationRecordVo = donationRecordService.queryObject(Integer.valueOf(recordId));

                if (donationRecordVo != null && donationRecordVo.getIsPay() == 0) {
                    donationRecordVo.setIsPay(1);
                    donationRecordVo.setTransactionId(transaction_id);
                    donationRecordService.update(donationRecordVo);
                    System.out.println("捐款记录更新成功");
                    //个人信息对应的字段更新
                    Integer userId = donationRecordVo.getUserId();
                    UserVo userVo = userService.queryObject((long) userId);
                    userVo.setLove_count(userVo.getLove_count() + 1);
                    userVo.setMy_donation(userVo.getMy_donation().add(donationRecordVo.getDonorAmount()));
                    userService.update(userVo);

                    //对应公益活动的字段更新
                    Integer commonwealId = donationRecordVo.getCommonwealId();
                    CommonwealVo commonwealVo = commonwealService.queryObject(commonwealId);
                    commonwealVo.setTotalFundraising(commonwealVo.getTotalFundraising().add(donationRecordVo.getDonorAmount()));
                    commonwealVo.setLoveCount(commonwealVo.getLoveCount() + 1);
                    commonwealService.update(commonwealVo);
                    System.out.println("公益活动更新成功");

                    //发送模板消息
                    setWxaConfig();//小程序配置信息
                    WxaTemplateApi wxaTemplateApi = Duang.duang(WxaTemplateApi.class);
                    WxaTemplate template = new WxaTemplate();
                    template.setForm_id(donationRecordVo.getPrepayId());//支付的prepay_id
                    template.setTouser(openId);//接收者（用户）的 openid
                    template.setTemplate_id(SuccessfulDonation);//购买成功通知的模板ID
                    template.setPage("pages/publicDetail/publicDetail?commonwealId=" + commonwealId);//小程序调转的页面:公益活动详情
                    template.add("keyword1", commonwealVo.getTitle());//项目名称
                    template.add("keyword2", donationRecordVo.getDonorAmount().toString());//捐款金额
                    template.add("keyword3", DateUtil.formatDateTime(donationRecordVo.getAddTime()));//捐款时间
                    String build = template.build();
                    ApiResult send = wxaTemplateApi.send(build);
                    Integer errorCode = send.getErrorCode();
                    if (errorCode != 0) {
                        System.out.println("模板发送失败信息：" + send.getErrorMsg());
                    }
                    System.out.println("模板信息发送成功");
                }

            }

            Map<String, String> xml = new HashMap<>();
            xml.put("return_code", "SUCCESS");
            xml.put("return_msg", "OK");
            String toXml = PaymentKit.toXml(xml);

            response.reset();
            PrintWriter out = response.getWriter();
            out.write(toXml);
            out.flush();
            out.close();

        } catch (IOException e) {
            logger.error("回调失败");
            e.printStackTrace();
        }

        return toResponsFail("下单失败");

    }
}
